<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="../css/reset.css">
    <style>
        .shadow{
            width: 200px;
            height: 200px;
            background-color: rgba(0,0,0,0.5);
            position: absolute;
            left: 100px;
            top: 100px;
        }
    </style>
</head>
<body>
    <div class="shadow"></div>
</body>
<script>
    // 需求: 元素拖拽  => 鼠标拖拽盒子移动

    // 1. 先按下 选中元素
    // 2. 再移动  => 元素相对于鼠标按下的位置移动
    // 3. 最后松开  => 元素不在移动

    var shadow = document.getElementsByClassName("shadow")[0];
    var isMoving = false;  //全局变量 => 记录是否被拖拽


    var posX = null;
    var posY = null;

    shadow.onmousedown = function(e){
        var e = e || window.event;
        
        posX = e.offsetX;
        posY = e.offsetY;
        console.log(posX,posY);

        isMoving = true;
    }

    document.onmousemove = function(e){
        if(!isMoving) return false;
        var e = e || window.event;
        var x = e.pageX - posX;
        var y = e.pageY - posY;
        console.log(x,y);

        shadow.style.left = x + "px";
        shadow.style.top = y + "px";
    }

    document.onmouseup = function(){
        isMoving = false;
    }

    



</script>
</html>